//
//  RansomNewController.m
//  LuCaiZhu
//
//  Created by 邓龙 on 2019/4/4.
//

#import "RansomNewController.h"
#import "HandleNetProduct+Transaction.h"
#import "RansomMangerController.h"
#import "TransactionController.h"
#import "UIColor+NN.h"
#import "UserModel.h"
#import "RansomNewCell.h"
#import "TKAlertCenter.h"

@interface RansomNewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *myNewTable;
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *noteLab;
@property (weak, nonatomic) IBOutlet UIView *bgView;

@property (nonatomic, strong) NSArray *detailInfo;
@property (nonatomic, strong) NSDictionary *dataDic;

@end

@implementation RansomNewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_isDetail) {
        self.title = @"订单明细";
        self.myNewTable.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
        _bottomConstraint.constant = 0;
        _bottomView.hidden = YES;
        
        [self getOrderDetailAction];
        [self getBottomDataAction];
    }
    else {
        self.title = @"新建赎回单";
//        [self xuxianSetAction];
        [self getJumpDataAction];
    }
    self.myNewTable.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void)xuxianSetAction {
    CAShapeLayer *border = [CAShapeLayer layer];
    
    //虚线的颜色
    border.strokeColor = [UIColor redColor].CGColor;
    //填充的颜色
    border.fillColor = [UIColor clearColor].CGColor;
    
    //设置路径
    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width-30, 110);
    border.path = [UIBezierPath bezierPathWithRect:rect].CGPath;
    
    border.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width-30, 110);;
    //虚线的宽度
    border.lineWidth = 1.f;
    
    
    //设置线条的样式
    //    border.lineCap = @"square";
    //虚线的间隔
    border.lineDashPattern = @[@4, @2];
    
    [self.bgView.layer addSublayer:border];
}

//获取订单明细
- (void)getOrderDetailAction {
    [HandleNetProduct getRansomOrderDetailInfoWithRansomId:[_redeemId intValue] Success:^(NSArray * _Nonnull data) {
        _detailInfo = data;
        [_myNewTable reloadData];
    } Failure:^(NSString * _Nonnull errorInfo) {
        
    }];
}

//获取订单明细底部数据
- (void)getBottomDataAction {
    [HandleNetProduct getRansomBottomInfoWithRansomId:[_redeemId intValue] Success:^(NSDictionary * _Nonnull data) {
        _dataDic = data;
        [_myNewTable reloadData];
    } Failure:^(NSString * _Nonnull errorInfo) {
        
    }];
}

//赎回编辑新建跳页数据
- (void)getJumpDataAction {
    NSDictionary *param = @{@"ContractNo": _createModel.ContractNo,
                            @"Share": _createModel.Redeemshare};
    [HandleNetProduct getJumpDataList:param Success:^(NSArray * _Nonnull data) {
        _detailInfo = data;
        
        NSString *str = [NSString stringWithFormat:@"%zd", data.count];
        NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"该产品的赎回规则是先进先出，需从购买时间最早的订单依次进行赎回，您的本次赎回涉及以下%@笔订单，请您知晓并确认：", str]];
        NSRange redRange = NSMakeRange([[contentStr string] rangeOfString:str].location, [[contentStr string] rangeOfString:str].length);
        [contentStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"FF0000"] range:redRange];
        
        [contentStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:redRange];
        [_noteLab setAttributedText:contentStr];
//        _noteLab.text = [NSString stringWithFormat:@"该产品的赎回规则是先进先出，需从购买时间最早的订单依次进行赎回，您的本次赎回涉及以下%zd笔订单，请您知晓并确认：", data.count];
        if (data.count > 1) {
            float cunxu = 0;
            float shenyu = 0;
            for (int i=0; i< data.count; i++) {
                NSDictionary *dic = data[i];
                shenyu += [[dic[@"RemainingShare"] stringByReplacingOccurrencesOfString:@"," withString:@""] doubleValue];
                cunxu += [[dic[@"SurvivingShare"] stringByReplacingOccurrencesOfString:@"," withString:@""] doubleValue];
            }
            _dataDic = @{@"TotalShare": [NSString stringWithFormat:@"%f", cunxu], @"SurplusShare": [NSString stringWithFormat:@"%f", shenyu]};
        }
        else {
            NSDictionary *dic = data.firstObject;
            _dataDic = @{@"TotalShare": dic[@"RemainingShare"], @"SurplusShare": dic[@"SurvivingShare"]};
        }
        
        [_myNewTable reloadData];
    } Failure:^(NSString * _Nonnull errorInfo) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return _detailInfo.count;
    }
    else {
        if (_dataDic) {
            return 1;
        }
        else {
            return 0;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (_isDetail) {
            return 260;
        }
        else {
            return 160;
        }
    }
    else {
        return 70;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (_isDetail && section == 0) {
        return 0;
    }
    else {
        return 10;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (_isDetail) {
            RansomNewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RansomNewCell2"];
            RansomOrderDetInfoModel *model = [RansomOrderDetInfoModel mj_objectWithKeyValues:_detailInfo[indexPath.row]];
            [cell setDetailInfoData:model];
            return cell;
        }
        else {
            RansomNewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RansomNewCell"];
            NSDictionary *dic = _detailInfo[indexPath.row];
            [cell setDataJumpAction:dic];
            return cell;
        }
    }
    else {
        RansomNewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RansomNewCell1"];
        if (!_isDetail) {
            if (_detailInfo.count > 1) {
                [cell setBottomData:_dataDic and:NO];
            }
            else {
                [cell setBottomData:_dataDic and:YES];
            }
        }
        else {
            [cell setBottomData:_dataDic and:_isDetail];
        }
        [cell setHiddenAction:_state];
        return cell;
    }
}

- (IBAction)bottomBtnAction:(UIButton *)sender {
    switch (sender.tag) {
        case 0:
            {
                __weak RansomNewController *weakSelf = self;
                if (_redeemId) {
                    if ([_createModel.Redeemshare floatValue] == [_ransomShare floatValue]) {
                        RansomMangerController *manage = nil;
                        TransactionController *transaction = nil;
                        for (UIViewController *controller in self.navigationController.viewControllers) {
                            if ([controller isKindOfClass:[RansomMangerController class]]) {
                                manage = (RansomMangerController *)controller;
                            }
                            if ([controller isKindOfClass:[TransactionController class]]) {
                                transaction = (TransactionController *)controller;
                            }
                        }
                        weakSelf.navigationController.viewControllers = @[transaction, manage];
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                        return;
                    }
                    UserModel *model=[UserModel getUser];
                    int mid=[model.CustomerID intValue];
                    NSDictionary *param = @{@"ReDeemId": _redeemId,
                                            @"Redeemshare": _createModel.Redeemshare,
                                            @"RedeemFee": _ransomCheckDic[@"RedeemFee"],
                                            @"SYShare": _ransomCheckDic[@"SYShare"],
                                            @"SYAmount": _ransomCheckDic[@"SYAmount"],
                                            @"ProductId": _createModel.ProductId,
                                            @"SubProductId": _createModel.SubProductId,
                                            @"AccountId": _createModel.CustomerID,
                                            @"OpenDate": _createModel.RedeemOpenDayShow,
                                            @"Currency": _createModel.Currency,
                                            @"ReferenceAmount": _createModel.ReferenceAmount,
                                            @"FaId": @(mid),
                                            @"ContractNo": _createModel.ContractNo};
                    [HandleNetProduct saveRansomShare:param Success:^(NSDictionary * _Nonnull data) {
                        [[TKAlertCenter defaultCenter]postAlertWithMessage:@"修改成功"];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            RansomMangerController *manage = nil;
                            TransactionController *transaction = nil;
                            for (UIViewController *controller in self.navigationController.viewControllers) {
                                if ([controller isKindOfClass:[RansomMangerController class]]) {
                                    manage = (RansomMangerController *)controller;
                                }
                                if ([controller isKindOfClass:[TransactionController class]]) {
                                    transaction = (TransactionController *)controller;
                                }
                            }
                            weakSelf.navigationController.viewControllers = @[transaction, manage];
                            [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                    } Failure:^(NSString * _Nonnull errorInfo) {
                        
                    }];
                }
                else {
                    UserModel *model=[UserModel getUser];
                    int mid=[model.CustomerID intValue];
                    NSDictionary *param = @{@"Redeemshare": _createModel.Redeemshare,
                                            @"RedeemFee": _ransomCheckDic[@"RedeemFee"],
                                            @"SYShare": _ransomCheckDic[@"SYShare"],
                                            @"SYAmount": _ransomCheckDic[@"SYAmount"],
                                            @"ProductId": _createModel.ProductId,
                                            @"SubProductId": _createModel.SubProductId,
                                            @"AccountId": _createModel.CustomerID,
                                            @"OpenDate": _createModel.RedeemOpenDayShow,
                                            @"Currency": _createModel.Currency,
                                            @"ReferenceAmount": _createModel.ReferenceAmount,
                                            @"FaId": @(mid),
                                            @"ContractNo": _createModel.ContractNo};
                    [HandleNetProduct addRansomNew:param Success:^(NSDictionary * _Nonnull data) {
                        RansomMangerController *manage = nil;
                        TransactionController *transaction = nil;
                        for (UIViewController *controller in self.navigationController.viewControllers) {
                            if ([controller isKindOfClass:[RansomMangerController class]]) {
                                manage = (RansomMangerController *)controller;
                            }
                            if ([controller isKindOfClass:[TransactionController class]]) {
                                transaction = (TransactionController *)controller;
                            }
                        }
                        weakSelf.navigationController.viewControllers = @[transaction, manage];
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                    } Failure:^(NSString * _Nonnull errorInfo) {
                        
                    }];
                }
            }
            break;
        case 1:
            [self.navigationController popViewControllerAnimated:YES];
            break;
    }
}

@end
